import { NavLink, useNavigate } from 'react-router-dom'
// import imgs from "../../../public/logo.png"
import React, { useEffect, useState } from 'react';
import { Button, Space, Table, Tag, Modal, Input, Form, message, Popconfirm } from 'antd';
import type { SizeType } from 'antd/es/config-provider/SizeContext';
import type { ColumnsType } from 'antd/es/table';
import { getuser, adduser, deluser } from '../../tools/ajax';
import {
    PlusOutlined,
    ImportOutlined,
} from '@ant-design/icons';
import "./manage.css"
import type { FormItemProps } from 'antd';

const MyFormItemContext = React.createContext<(string | number)[]>([]);

interface MyFormItemGroupProps {
    prefix: string | number | (string | number)[];
    children: React.ReactNode;
}

function toArr(str: string | number | (string | number)[]): (string | number)[] {
    return Array.isArray(str) ? str : [str];
}

const MyFormItemGroup = ({ prefix, children }: MyFormItemGroupProps) => {
    const prefixPath = React.useContext(MyFormItemContext);
    const concatPath = React.useMemo(() => [...prefixPath, ...toArr(prefix)], [prefixPath, prefix]);

    return <MyFormItemContext.Provider value={concatPath}>{children}</MyFormItemContext.Provider>;
};

const MyFormItem = ({ name, ...props }: FormItemProps) => {
    const prefixPath = React.useContext(MyFormItemContext);
    const concatName = name !== undefined ? [...prefixPath, ...toArr(name)] : undefined;

    return <Form.Item name={concatName} {...props} />;
};


function Manager() {
    // 表格
    interface DataType {
        key: string;
    }
    const columns: ColumnsType<DataType> = [
        {
            title: '姓名',
            dataIndex: 'userName',
            key: "userName",
            render: (text) => <a>{text}</a>,
        },
        {
            title: '密码',
            dataIndex: 'password',
            key: "password",
        },
        {
            title: '删除',
            // dataIndex: 'userId',
            // key: "userId",
            //函数式声明：text表示当前行内容
            render: (text) => (<Space size="middle">
                <Popconfirm //ant组件
                    title="您确定要删除吗？"
                    onConfirm={() => {
                        confirm(text); //调用当前confirm进行删除
                    }}
                    okText="确定"
                    cancelText="取消"
                >
                    <Button danger type="primary">删除</Button>
                </Popconfirm>
            </Space>)
        },
    ]

    // 删除用户
    function confirm(e) {
        // console.log(e.userId);
        deluser({
            userId: e.userId,
            token: localStorage.getItem("token")
        }).then(res => {
            if (res.data.code == 2) {
                messageApi.open({
                    type: 'success',
                    content: '删除成功',
                });
                // 刷新列表
                getqing()
            }
        })
    }
    const [messageApi, contextHolder] = message.useMessage();
    const [size, setSize] = useState<SizeType>('large');
    const navgate = useNavigate()
    // 返回首页
    function backindex() {
        navgate("/home")
    }
    // 用户列表
    const [userlist, setUserlist] = useState([])
    useEffect(() => {
        getqing()
    }, [])
    function getqing() {
        getuser({
            token: localStorage.getItem("token")
        }).then(res => {
            // console.log(res);
            setUserlist(res.data)
        })
    }

    // 添加用户提示
    const [isModalOpen, setIsModalOpen] = useState(false);
    const showModal = () => {
        setIsModalOpen(true);
    };
    const handleOk = () => {
        setIsModalOpen(false);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };
    const onFinish = (value: object) => {
        console.log(value);
        console.log(value.user.name.count, value.user.name.password);
        adduser({
            userName: value.user.name.count,
            password: value.user.name.password,
            token: localStorage.getItem("token")
        }).then(res => {
            console.log(res);
            if (res.data.code == 3) {
                messageApi.open({
                    type: 'success',
                    content: '添加成功',
                });
                handleCancel()
                getqing()
            } else {
                messageApi.open({
                    type: 'error',
                    content: '用户名被占用',
                });
            }
        }, [])
    };

    return <div className="my_homes">
        {contextHolder}
        <div className='my_top'>
            <div className='img'><img src={imgs} /></div>
            <div><h2>中国移动业务报价系统</h2></div>
            <div className='my_btn'>
                <>
                    <Button type='primary' onClick={showModal} className='my_t' size={size}><Space><PlusOutlined /></Space>添加用户</Button>
                    <Modal title="添加用户" centered={true} footer={null} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} >
                        <div className="my_user">
                            <Form name="form_item_path" layout="horizontal " onFinish={onFinish}>
                                <MyFormItemGroup prefix={['user']}>
                                    <MyFormItemGroup prefix={['name']}>
                                        <MyFormItem name="count" label="账号" >
                                            <Input />
                                        </MyFormItem>
                                        <MyFormItem name="password" label="密码">
                                            <Input />
                                        </MyFormItem>
                                    </MyFormItemGroup>
                                </MyFormItemGroup>
                                <Button type="primary" htmlType="submit">
                                    提交
                                </Button>
                            </Form>
                        </div>
                    </Modal>
                </>
                <Button ghost size={size} onClick={backindex}><Space><ImportOutlined /></Space>返回首页</Button>
            </div>
        </div>
        {/* 用户信息 */}

        <Table bordered align={"center"}
            pagination={false}
            scroll={{ y: 530 }}
            columns={columns} dataSource={userlist} />
    </div>
}
export default Manager
